package com.quan.api.wx.oauth;

import cn.hutool.core.util.URLUtil;

import com.quan.commons.core.biz.support.MyBaseController;
import com.quan.commons.core.properties.SystemValueProperties;
import com.quan.mall.commons.vo.UmsMemberVo;
import com.quan.mall.entity.UmsMember;
import com.quan.mall.service.UmsMemberService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信公众号授权
 * 
 * @author yhaoquan
 *
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/api/wx/h5")
public class ApiWxH5OAuthController extends MyBaseController {
	
	@Autowired
	private UmsMemberService umsMemberService;

	@Autowired
	private WxMpService wxMpService;

	@Autowired
	private SystemValueProperties properties;
	
	/**
	 * 微信授权入口
	 * @throws Exception
	 */
	@GetMapping(value = "authorize")
	public void authorize() throws Exception {
		log.debug("==>1、微信网页授权，引导用户到授权页面");

		// 授权回调地址
		String redirectUrl = this.properties.getWechat().getOauthCallbackUrl() ;

		try {
			final String authorizationUrl = this.wxMpService.getOAuth2Service().buildAuthorizationUrl(redirectUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
			this.response.sendRedirect(authorizationUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 网页授权回调处理方法
	 */
	@GetMapping("callback")
	public void callback() {
		log.debug("==>2、微信网页授权，回调处理");
		try {
			// 授权完后，默认跳转的页面
			String redirectUrl = "";

			// 1、接收微信传回的code参数
			String code = request.getParameter("code");
			// 2、通过Code换取access_token的票据
			final WxOAuth2AccessToken accessToken = this.wxMpService.getOAuth2Service().getAccessToken(code);
			// 3、通过access_token获取用户信息
			final WxOAuth2UserInfo userInfo = this.wxMpService.getOAuth2Service().getUserInfo(accessToken, null);

			// 获取会员信息
			UmsMember member = this.umsMemberService.getMemberByOpenId(userInfo.getOpenid());

			// 会员未注册
			if(null == member) {

				// 将会员信息保存
				UmsMemberVo memberVo = new UmsMemberVo();
				memberVo.setOpenid(userInfo.getOpenid());
				memberVo.setAvatar(userInfo.getHeadImgUrl());
				memberVo.setNickname(userInfo.getNickname());
				memberVo.setRegSrc(3);
				this.umsMemberService.register(memberVo);
			}

			// 携带OPENID跳转到H5首页
			redirectUrl = this.properties.getWechat().getH5HomeUrl() + "?openId=" + userInfo.getOpenid();


			log.debug("==>微信授权登录成功==>昵称：{}，openid：{}，跳转的路径：{}", userInfo.getNickname(), userInfo.getOpenid(), redirectUrl);

			this.response.sendRedirect(redirectUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
